CommonUtils.regNamespace("com.im.inverstApply");
com.im.inverstApply.invoke = function() {
	var param = {
		pageNumber: 1,
	    pageSize: 20
	};
    var client = new com.im.common.ajax();
    var operType = "";
    var inverstApply;
    function _init() {
        //加载列表信息
    	_initDataList();
    	//重置按钮
    	$('#ResetBtn').click(function (){
    		_resetSearchInfo();
    	});
        //查询按钮
        $("#SearchBtn").click(function(){
        	_loadDataList(true);
        });
        //新增弹出按钮
        $("#addBtn").click(function(){
        	_addInverstApply();
        });
        //新增编辑保存按钮
        $("#saveBtn").click(function(){
        	_saveInverstApply();
        });
        
        //实施项目
	    $("#itemBtn").click(function() {
	        $("#itemBtn").itemSearchCommpent({
	            elmIdOut : "impleProjName",
	            elmIdModal : "itemSearchModal",
	            elmIdOrgModal : "unitSearchModal3",
	            callbackFunc: function (projectId, projectName) {
	            	$("#impleProjName").val(projectName).trigger("change");
	                $("#impleProjId").val(projectId).trigger("change");
	            }
	        });
	    });
        var statusCdList=[{"id":"20","text":"关闭填报"},{"id":"10","text":"开放填报"}];
        var statusCdSelect = $("#statusCd");
        $.each(statusCdList, function (i, item) {
            if(i == 0) {
            	statusCdSelect.append("<option statusCdId='" + item.id + "' selected='selected'>" + item.text + "</option>");
            } else {
            	statusCdSelect.append("<option statusCdId='" + item.id + "'>" + item.text + "</option>");
            }
        });

        //复选框
        $('input[type="checkbox"].minimal, input[type="radio"].minimal').iCheck({
          checkboxClass: 'icheckbox_minimal-blue',
          radioClass   : 'iradio_minimal-blue'
        });
        //下拉框
        $('.select2').select2();
        //验证
        _formValidator();
        //重置验证
        $('#addEditModal').on('hidden.bs.modal', function() {
        	_reset();
        });

        //时间插件
        $('#yearDt').datepicker({
            startView: 'decade',
            minView: 'decade',
            format: 'yyyy',
            maxViewMode: 2,
            minViewMode:2,
            autoclose: true
        });
        $('#endDt').datepicker({
            todayHighlight:true,
            todayBtn: 'linked',
            keyboardNavigation:true,
            autoclose:true,
            language:'zh-CN',
            format:'yyyy-mm-dd'
        });

        //批量时间
        $("#batchOpenBtn").click(function () {
			_batchOper('10');
        });
        $("#batchCloseBtn").click(function () {
			_batchOper('20');
        })
    };

    function _batchOper(type){
        var checkedItems = $('#inverstPlanSetList').datagrid('getChecked');

        var olist = [];
        $.each(checkedItems,function (i,obj) {
        	//开放，且为关闭状态
			if(type ==  '10' && obj.statusCd == '20'){
				olist.push(obj.declareSetId);
			}
			//关闭，且为开发状态
			if(type ==  '20' && obj.statusCd == '10'){
                olist.push(obj.declareSetId);
			}
        });

        if(olist.length > 0){
            var param = {};
            param.declareSetIds = olist;
            param.statusCd = type;

            var result = client.callAsJson("investPlanService/updateInvestPlanSetByCondition", param);
            if(result.resultCode=='0'){

                toastr.success("操作成功！");
                _loadDataList();
            }else {
                toastr.error("服务器忙！请稍后再试！"+result.resultMsg);
            }
		}else{
            toastr.success("操作成功！");
		}
    }
    //重置搜索条件
    function _resetSearchInfo(){
    	$('#searchImpleProjName,#searchDeclareSetName').val('');
    }
    //更新数据列表
    function _loadDataList(pageNumber){
    	var impleProjName = $("#searchImpleProjName").val();
        var investPlanName = $("#searchDeclareSetName").val();
        param.impleProjName = impleProjName;
        param.investPlanName = investPlanName;
        if(pageNumber){
    		param.pageNumber = 1;
            $('#inverstPlanSetList').datagrid("load",param);
        }else{
    	   $('#inverstPlanSetList').datagrid("reload",param);
        }
    }
    //新增编辑(保存按钮)
    function _saveInverstApply(){
    	$("#inverstApplyForm").data("bootstrapValidator").validate();
    	var flag = $("#inverstApplyForm").data("bootstrapValidator").isValid();
    	if(flag){
	    	var saveparam={};
	    	saveparam.investPlanCode= $("#investPlanCode").val();
	    	saveparam.investPlanName= $("#declareSetName").val();
	    	saveparam.investPlanId= $("#investPlanId").val();
	    	saveparam.impleProjId= $("#impleProjId").val();
	    	saveparam.description= $("#description").val();
	    	saveparam.yearDt = $("#yearDt").val()+'-01-01';//后端格式化报错
	    	saveparam.endDt = $("#endDt").val();
	    	saveparam.statusCd= $("#statusCd  option:selected").attr('statuscdid');
	    	 var declareSetId= $("#declareSetId").val();
	    	 if(declareSetId!=''){
	    		 saveparam.declareSetId= declareSetId;
	    	 }
	    	 saveparam.enterRequest = $("#enterRequest").val() == '' ? '开放填报' : $("#enterRequest").val();//新增时enterRequest、docCode暂时给固定值
	    	 saveparam.docCode = $("#docCode").val() == '' ? 'ios-10000' : $("#docCode").val();
	    	 if(declareSetId!=''){
	    		 var result = client.callAsJson("investPlanService/updateInvestPlanSet", saveparam);
	    		 if(result.resultCode=='0'){
	    			 $("#addEditModal").modal("hide");
	 		        toastr.success("保存成功！");
	    			 _loadDataList();
	    		 }else {
	                 toastr.error("服务器忙！请稍后再试！"+result.resultMsg);
	             }
	    	 }else{
	    		 saveparam.docCode='IOS-999999';
	    		 saveparam.enterRequest='填报要求';
	    		 saveparam.declareType='10';
	    		 var result = client.callAsJson("investPlanService/addInvestPlanSet", saveparam);
	    		 if(result.resultCode=='0'){
	    			 $("#addEditModal").modal("hide");
	 		        toastr.success("保存成功！");
	    			 _loadDataList();
	    		 }else {
	                 toastr.error("服务器忙！请稍后再试！"+result.resultMsg);
	             } 
	    	 }	
    	}
    	  
    }
  //验证
    function _formValidator(){
    	$("#inverstApplyForm").bootstrapValidator({
    	    feedbackIcons: {
    	      valid: 'glyphicon glyphicon-ok',
    	      invalid: 'glyphicon glyphicon-remove',
    	      validating: 'glyphicon glyphicon-loadData'
    	    },
    	    excluded: [':hidden', ':not(:visible)'],
    	    fields: {
    	    	declareSetName:{
    	    		validators: {
  	    	          notEmpty: {
  	    	            message: '投资计划批次不能为空'
  	    	          }
  	    	        }
    	    	}/*,
    	    	impleProjName: {
    	            trigger:"change",
	    	        validators: {
	    	          notEmpty: {
	    	            message: '实施项目不能为空'
	    	          }
	    	        }
    	    	}*/,
    	    	statusCd: {
	    	        validators: {
	    	          notEmpty: {
	    	            message: '状态不能为空'
	    	          }
	    	        }
    	    	}
                ,
                yeahDt: {
                    validators: {
                        notEmpty: {
                            message: '年份不能为空'
                        }
                    }
                }
                ,
                endDt: {
                    validators: {
                        notEmpty: {
                            message: '截止时间不能为空'
                        }
                    }
                }
    	    }
    	  });
    }
    //重置验证
    function _reset(){
    	$("#inverstApplyForm").data('bootstrapValidator').destroy();
        $('#inverstApplyForm').data('bootstrapValidator', null);
        _formValidator();
    }
    //新增操作
    function _addInverstApply(index){
    	 $("#addEditModal .modal-title").html("投资计划申报");
    	 _showInverstApply();
         $("#addEditModal").modal("show");
    }
    //删除操作
    function _delInverstApply(index){
    	com.im.common.confirm("确认是否删除", null, function () {
       	    inverstApply = $('#inverstPlanSetList').datagrid('getData').rows[index];
            if(inverstApply.statusCd != "开放填报") {
                toastr.error("只允许删除【开放填报】投资计划");
                return;
            }
            var result = client.callAsJson("investPlanService/updateInvestPlanSet", {'declareSetId':inverstApply.declareSetId,'statusCd':'30'});
      	  	if (result.resultCode=="0") {
  		      toastr.success("删除成功！");
      		  _loadDataList();
            } else {
                toastr.error("服务器忙！请稍后再试！"+result.resultMsg);
            }
        });
    }
    //编辑操作
    function _modInverstApply(index){
    	 $("#addEditModal .modal-title").html("投资计划修改");
    	 inverstApply = $('#inverstPlanSetList').datagrid('getData').rows[index];
          // var result = client.callAsJson("investPlanService/queryInvestPlanSetDetail", {'declareSetId':inverstApply.declareSetId});
          // if (result.resultCode=="0") {
          //     if(result.result!= null){
          //   	  _showInverstApply(result.result);
          //     }
          // } else {
          //     toastr.error("服务器忙！请稍后再试！"+result.resultMsg);
          // }
        _showInverstApply(inverstApply);
         $("#addEditModal").modal("show");
    }
    //新增编辑模态框数据初始化
    function _showInverstApply(inverstApply){
    	if(inverstApply==null){
        	 var result = client.callAsJson("commonService/getSeq", {'tableName':'T_INVEST_PLAN'});
        	 $("#investPlanCode").val(result.result.seq);
             $("#declareSetName").val("");
             $("#impleProjName").val("");
             $("#description").val("");
             $("#declareSetId").val("");
             $("#impleProjId").val("");
             $("#impleProjName").attr('projectid',"");
             $("#investPlanId").val("");
             $("#enterRequest").val("");
             $("#docCode").val("");
             $("#statusCd option").attr("selected",false);
             $("#statusCd option[statusCdId='20']").attr("selected",true);
             $("#statusCd").val($("#statusCd option[statusCdId='20']").html()).trigger("change");

             $("#yearDt").val("");
             $("#endDt").val("");

    	}else{
    		  $("#investPlanId").val(inverstApply.declareRelaObj);
    		  $("#investPlanCode").val(inverstApply.investPlanCode);
              $("#declareSetName").val(inverstApply.investPlanName);
              $("#declareSetId").val(inverstApply.declareSetId);
              $("#impleProjName").val(inverstApply.impleProjName);
              $("#description").val(inverstApply.description);
              $("#impleProjId").val(inverstApply.impleProjId);
              $("#impleProjName").attr('projectid',inverstApply.impleProjId);
              $("#enterRequest").val(inverstApply.enterRequest);
              $("#docCode").val(inverstApply.docCode);
              $("#statusCd").val($("#statusCd option[statusCdId='"+inverstApply.statusCd+"']").html()).trigger("change");
              $("#yearDt").val(inverstApply.yearDt);
              $("#endDt").val(inverstApply.endDt);
    	}
    }
    
    //初始化表格数据
    function _initDataList(){
    	var columns=[[
            {field:'全选',title:"全选",width:30,checkbox:true,fitColumns:true},
            {field:'序号',title:"序号",width:25,fitColumns:true,
    	              	formatter: function(value,row,index){
    	                      return  index+1;
    	                  }
    	    },
            {field:'yearDt',title:"年份",width:50,fitColumns:true,align:'center'},
            {field:'investPlanCode',title:"投资计划申报编码",width:150,fitColumns:true,align:'center'},
    	    {field:'investPlanName',title:"投资计划申报批次",width:100,fitColumns:true,align:'center'},
    	    //{field:'impleProjName',title:"实施项目名称",width:100,fitColumns:true,align:'center'},
    	    {field:'description',title:"备注",width:120,fitColumns:true,align:'center'},
    	    {field:'endDt',title:"截止填报时间",width:80,fitColumns:true,align:'center'},
    	    {field:'statusName',title:"状态",width:100,fitColumns:true,align:'center'},
    	    {field:'operation',title:"操作",width:100,align:'center',
    	        formatter: function(value,row,index){
    	            return  '<a href="javascript:; "onclick="com.im.inverstApply.invoke.modInverstApply(\''+index+'\')" title="修改"><i class="fa fa-edit"></i></a> '+
    	                    '<a href="javascript:; "onclick="com.im.inverstApply.invoke.delInverstApply(\''+index+'\')" title="删除"><i class="fa fa-trash"></i></a>';
    	        }},
    	]];
    	$('#inverstPlanSetList').datagrid({
    	    url:'/InfoManageWeb/investPlanService/queryInvestPlanSetList',
    	    method:'post',
    	    dataType : 'json',
    	    queryParams:param,
    	    pagination:true,
    	    nowrap:false,
    	    fitColumns:true,
    	    columns:columns,
    	    loadMsg:'数据加载中，请耐心等待',
    	    onBeforeLoad : function(param){
	    	    for (var key in param) {
		    	    if(key=="rows"){
		    	    	delete param[key];
		    	    }
		    	}
    	    },
    	    loadFilter:function(data){
    	      if(data.resultCode!=0){
    	        toastr.error(data.resultCode);
    	        return null;
    	      }else{
    	        return data.result;
    	      }
    	    },
    	});
    	var p = $('#inverstPlanSetList').datagrid('getPager');
    	  $(p).pagination({
    	    pageSize: 20,
    	    pageList: [10,20,30],
    	    beforePageText: '第',
    	    afterPageText: '页    共 {pages}  页',
    	    displayMsg: '当前显示 {from} - {to} 条记录 共 {total}  条记录',
    	    onSelectPage:function(pageNumber, pageSize){
    	      param.pageNumber=pageNumber;
    	      param.pageSize=pageSize;
    	      var impleProjName = $("#searchImpleProjName").val();
    	      var investPlanName = $("#searchDeclareSetName").val();
    	      param.impleProjName = impleProjName;
    	      param.investPlanName = investPlanName;
    	      $('#inverstPlanSetList').datagrid('reload',param);
    	    }
    	  });
    	  
    	  function DateTimeFormatter(value) {
    		    if (value == undefined) {
    		        return "";
    		    }
    		    /*json格式时间转js时间格式*/
    		    value = value.substr(1, value.length - 2);
    		    var obj = eval('(' + "{Date: new " + value + "}" + ')');
    		    var dateValue = obj["Date"];
    		    if (dateValue.getFullYear() < 1900) {
    		        return "";
    		    }

    		    return dateValue.format("yyyy-MM-dd hh:mm:ss");
    		}
    }

	return {
		init : _init,
		delInverstApply : _delInverstApply,
        modInverstApply : _modInverstApply
	}
}();

$(function() {
	com.im.inverstApply.invoke.init();
});
